package cn.xorange.commons.utils.http;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.xorange.commons.utils.configuration.constants.UtilsConstants;
import cn.xorange.commons.utils.exception.UtilsException;
import cn.xorange.commons.utils.lang.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
public class ServletUtils {
    private ServletUtils(){}

    public static void responseSuccessOut(HttpServletResponse response, Serializable data) {
        responseOut(response,200,0,"请求成功",data);
    }

    public static void responseOut(HttpServletResponse response, Integer status, Integer code, String msg , Serializable data) {

        JSONObject obj = new JSONObject();
        obj.put("status", status);
        obj.put("code", code);
        obj.put("msg", msg);

        if(Objects.nonNull(data)){
            obj.put("data", data);
        }

        response.setContentType("application/json;charset=utf-8");
        response.setStatus(status);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(obj.toJSONString());
            writer.flush();
        } catch (IOException e) {
            log.debug("responseOut:" + e.getMessage());
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }




    }


    /**
     * 是否为http(s)://开头
     *
     * @param link 链接
     * @return 结果
     */
    public static boolean isHttp(String link) {
        return StrUtil.startWithAny(link, UtilsConstants.HTTP, UtilsConstants.HTTPS);
    }

    /**
     * 是否是Ajax异步请求
     *
     * @param request
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String accept = request.getHeader("accept");
        if (accept != null && accept.contains("application/json")) {
            return true;
        }

        String xRequestedWith = request.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
            return true;
        }

        String uri = request.getRequestURI();
        if (StringUtils.containsIgnoreCase(uri, ".json", ".xml")) {
            return true;
        }

        String ajax = request.getParameter("__ajax");
        return StringUtils.containsIgnoreCase(ajax, "json", "xml");
    }

    /**
     * 内容编码
     *
     * @param str 内容
     * @return 编码后的内容
     */
    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, String.valueOf(StandardCharsets.UTF_8));
        }
        catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    /**
     * 内容解码
     *
     * @param str 内容
     * @return 解码后的内容
     */
    public static String urlDecode(String str) {
        try {
            return URLDecoder.decode(str, String.valueOf(StandardCharsets.UTF_8));
        }
        catch (UnsupportedEncodingException e) {
            return "";
        }
    }



    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
        }
        return map;
    }
    public static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        return Objects.requireNonNull(getRequestAttributes()).getResponse();
    }
    /**
     * 获取session
     */
    public static HttpSession getSession()
    {
        return getRequest().getSession();
    }
    /**
     * 获取属性
     */
    public static Object getAttribute(String name) {
        return getRequest().getAttribute(name);
    }

    /**
     * 获取参数
     */
    public static String getParameter(String name) {
        return getRequest().getParameter(name);
    }

    /**
     * 获取String参数
     */
    public static String getParameter(String name, String defaultValue) {
        return Convert.toStr(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name)
    {
        return Convert.toInt(getRequest().getParameter(name));
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name, Integer defaultValue) {
        return Convert.toInt(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取request json
     * @param request
     * @return
     */
    public static JSONObject getParamJsonObj(HttpServletRequest request){
        try{
            ServletInputStream sis = request.getInputStream();
            StringBuilder sb = new StringBuilder();
            byte[] b = new byte[1024];
            int lens;
            while ((lens = sis.read(b)) > 0){
                sb.append(new String(b,0,lens));
            }
            return JSON.parseObject(sb.toString());

        }catch (IOException e){
            throw UtilsException.systemException("getParamJsonObj");
        }


    }

    //public static String getAopRequestParams(ProceedingJoinPoint joinPoint){
    //    try {
    //        // 下面两个数组中，参数值和参数名的个数和位置是一一对应的。
    //        Object[] objs = joinPoint.getArgs();
    //        String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames(); // 参数名
    //        Map<String, Object> paramMap = new HashMap<>();
    //        for (int i = 0; i < objs.length; i++) {
    //            if (!(objs[i] instanceof ExtendedServletRequestDataBinder) && !(objs[i] instanceof HttpServletResponseWrapper)) {
    //                paramMap.put(argNames[i], objs[i]);
    //            }
    //        }
    //        if (!paramMap.isEmpty()) {
    //            return JSON.toJSONString(paramMap);
    //        }else {
    //            return null;
    //        }
    //    } catch (Exception e) {
    //        throw UtilsException.systemException("getAopRequestParams");
    //    }
    //}



}
